<template>
  <BaseDialog
    :visible="visible"
    :title="isEdit ? '编辑组织' : '新增组织'"
    width="500px"
    @update:visible="handleUpdateVisible"
    @confirm="handleConfirm"
    @cancel="handleCancel"
    :confirm-loading="loading"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="80px"
      size="default"
    >
      <el-form-item label="组织名称" prop="name">
        <el-input
          v-model="formData.name"
          placeholder="请输入组织名称"
        />
      </el-form-item>

      <el-form-item label="上级组织" prop="parentId">
        <el-tree-select
          v-model="formData.parentId"
          :data="organizeStore.organizeTree"
          :props="treeProps"
          placeholder="请选择上级组织"
          style="width: 100%"
          :render-after-expand="false"
          check-strictly
        />
      </el-form-item>
    </el-form>
  </BaseDialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { ElForm, ElFormItem, ElInput, ElTreeSelect } from 'element-plus'
import BaseDialog from '@/components/BaseDialog.vue'
import { useOrganizeStore } from '@/stores/organize'
import { error } from '@/utils/toast'
import type { OrganizeTreeNode } from '@/types'

// Props
interface Props {
  visible: boolean
  organizeData?: OrganizeTreeNode | null
  parentId?: number
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  organizeData: null,
  parentId: 0
})

// Emits
const emit = defineEmits<{
  'update:visible': [value: boolean]
  'success': []
}>()

// 使用store
const organizeStore = useOrganizeStore()

// 响应式数据
const formRef = ref<InstanceType<typeof ElForm>>()

// 树形选择器配置
const treeProps = {
  children: 'children',
  label: 'name',
  value: 'id'
}

// 表单数据
const formData = reactive({
  name: '',
  parentId: 0,
  code: '', // 空字符串
  abbreviation: '' // 空字符串
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入组织名称', trigger: 'blur' },
    { min: 2, max: 50, message: '组织名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  parentId: [
    { required: true, message: '请选择上级组织', trigger: 'change' },
    {
      validator: (_rule: any, value: number, callback: Function) => {
        if (!isEdit.value && value === 0) {
          callback(new Error('新增组织时必须选择上级组织'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
}

// 计算属性
const isEdit = computed(() => !!props.organizeData)
const loading = computed(() => organizeStore.loading)

// 监听visible变化
watch(() => props.visible, (newVal) => {
  if (newVal) {
    initForm()
  }
})

// 监听organizeData变化
watch(() => props.organizeData, (newVal) => {
  if (newVal && props.visible) {
    initForm()
  }
})

// 监听组织树数据变化，确保新增时默认选中根节点
watch(() => organizeStore.organizeTree, (newTree) => {
  if (newTree && newTree.length > 0 && props.visible && !isEdit.value) {
    // 新增模式下，如果当前parentId为0，则设置为根节点
    if (formData.parentId === 0) {
      const rootNodeId = getRootNodeId()
      formData.parentId = rootNodeId
    }
  }
}, { deep: true })

// 方法
const initForm = () => {
  if (props.organizeData) {
    // 编辑模式
    Object.assign(formData, {
      name: props.organizeData.name || '',
      parentId: props.organizeData.parentId || 0,
      code: props.organizeData.code || '',
      abbreviation: props.organizeData.abbreviation?.toString() || ''
    })
  } else {
    // 新增模式 - 默认选中根节点
    const rootNodeId = getRootNodeId()
    Object.assign(formData, {
      name: '',
      parentId: props.parentId || rootNodeId || 0,
      code: '', // 空字符串
      abbreviation: '' // 空字符串
    })
  }
  
  // 清除验证
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

// 获取根节点ID
const getRootNodeId = () => {
  if (organizeStore.organizeTree && organizeStore.organizeTree.length > 0) {
    // 找到parentId为0的根节点
    const rootNode = organizeStore.organizeTree.find(node => node.parentId === 0)
    return rootNode ? rootNode.id : organizeStore.organizeTree[0].id
  }
  return 0
}


// 组织选项已经在store中管理，无需单独加载

const handleUpdateVisible = (value: boolean) => {
  emit('update:visible', value)
}

const handleCancel = () => {
  emit('update:visible', false)
}

const handleConfirm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    const submitData = {
      ...formData
    }
    
    if (isEdit.value && props.organizeData) {
      await organizeStore.updateOrganize( {...submitData, id: props.organizeData.id})
    } else {
      await organizeStore.createOrganize(submitData)
    }
    
    emit('success')
    emit('update:visible', false)
  } catch (err) {
    if (err !== false) { // 表单验证失败时err为false
      error('操作失败')
    }
  }
}
</script>

<style scoped lang="scss">
:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input__wrapper) {
  border-radius: 4px;
}

:deep(.el-select .el-input__wrapper) {
  border-radius: 4px;
}

:deep(.el-tree-select .el-input__wrapper) {
  border-radius: 4px;
}
</style>
